import os
import utils.XmMovie
import json
from pathlib import Path
import time
import test.test1
from pydub import AudioSegment
import Levenshtein
import datetime


def get_names(names_file, prefix):
    names = []
    with open(names_file, 'r') as names_file:
        content = names_file.read()  # 读取文件全部内容
        arr = content.split("\n")
        for i in range(len(arr)):
            name = arr[i]
            if len(name.strip()) > 0:
                new_name = f"{prefix}%02d %s" % (i, name)
                names.append(new_name)
    return names

def get_files(dir, exts):
    list = []
    files_and_folders = os.listdir(dir)
    for item in files_and_folders:
        path = Path(item)
        # print(path.suffix[1:], exts, path.suffix in exts)
        if(path.suffix[1:] in exts):
            list.append(os.path.join(dir, item))

    list = sorted(list)

    return list
def format_imgs_name(dir):
    files_and_folders = os.listdir(dir)
    for item in files_and_folders:
        path = Path(item)
        print('path.name', path.name[0:-len(path.suffix)])

def rename_file(origin_file, new_name):
    path = Path(origin_file)
    dir = os.path.dirname(origin_file)
    suffix = path.suffix
    new_path = os.path.join(dir, new_name+suffix)
    os.rename(origin_file, new_path)


def batch_make_video(names, imgs, audios, output_dir):
    attachs = []
    for i in range(len(names)):
        # print(f'{i}' , i%2, names[i])
        attachs.append({
            'idx': i,
            'name': names[i],
            'audio': audios[i],
            'img1': imgs[i*2],
            'img2': imgs[i*2 +1],
        })

    for item in attachs:
        idx = item['idx']
        name = item['name']
        audio = item['audio']
        img1 = item['img1']
        img2 = item['img2']
        out_name = f"%s.mp4" % (name)
        out_file = os.path.join(output_dir, out_name)
        # print(out_file)
        utils.XmMovie.make_video(output=out_file, img1=img1, img2=img2, audio=audio)


def rename_files(origin_names, imgs, audios):
    for i in range(len(origin_names)):
        img1 = imgs[i*2]
        img2 = imgs[i*2+1]
        audio = audios[i]
        name = origin_names[i]

        rename_file(img1, name+'_1')
        rename_file(img2, name+'_2')
        rename_file(audio, name)

def get_all_files(resource, month):
    prefix = month[3:6]
    if (resource == 'resource1'):
        prefix = f"初%s" % (prefix)
    elif (resource == 'resource1'):
        prefix = f"小%s" % (prefix)
    elif (resource == 'resource1'):
        prefix = f"幼%s" % (prefix)

    print('prefix:', prefix)

    name_file = f'{resource}/{month}/name-list.txt'
    names = get_names(name_file, prefix)
    # for i in range(len(names)):
    #     print(names[i])

    # format_imgs_name(f'{resource}/{month}/imgs')
    # return

    audios = get_files(f'{resource}/{month}/audios', exts=['wma', 'wav'])
    # for i in range(len(wma_audios)):
    #     print(f"{i}:",wma_audios[i])

    imgs = get_files(f'{resource}/{month}/imgs', exts=['png', 'jpg', 'jpeg'])
    # for i in range(len(imgs)):
    #     print(f"{i}:", imgs[i])


    return {
        'names': names,
        'imgs': imgs,
        'audios': audios,
    }

def make_datas(resource, month, names, imgs, audios):
    for i in range(len(names)):

        data_dir = f'{resource}/{month}/datas/'
        data_file = os.path.join(data_dir, f'{names[i]}.json')

        if not os.path.exists(data_dir):
            os.mkdir(data_dir)

        if os.path.exists(data_file):
            print("文件已存在：", data_file)
            continue

        item = {}
        img1 = imgs[i * 2]
        img2 = imgs[i * 2 + 1]
        item['name'] = names[i]
        item['audio'] = audios[i]
        item['img1'] = img1
        item['img2'] = img2
        item['txt1'] = utils.XmMovie.ocr_img_words(img1)
        item['txt2'] = utils.XmMovie.ocr_img_words(img2)
        item['audio_text'] = utils.XmMovie.parse_audio_text(audios[i])

        with open(data_file, 'w') as file:
            item_json = json.dumps(item, indent=4, ensure_ascii=False)
            print("item_json", names[i], item_json)
            file.write(item_json)
            file.close()

def convert_wma_wav(wma_dir, wav_dir):
    wma_audios = get_files(wma_dir, ['wma'])
    if not os.path.exists(wav_dir):
        os.mkdir(wav_dir)

    for i in range(len(wma_audios)):
        wma = wma_audios[i]
        # 从wma文件加载音频
        path = Path(wma)
        name = path.name
        ext = path.suffix
        base_name = name[0: -len(ext)]
        new_name = f'{base_name}.wav'
        out_path = os.path.join(wav_dir,new_name)
        print('name:', name)
        print('base_name:', base_name)
        print('new_name:', new_name)
        print('out_path:', out_path)

        if os.path.exists(out_path):
            print("文件已存在:", new_name)
            continue

        # 将音频保存为wav格式
        ffmpeg.input(wma).output(out_path).run()
        if not os.path.exists(out_path):
            raise FileExistsError(f"Output file:{out_path} was not successfully generated")

        info2 = ffmpeg.probe(out_path)
        streams2 = info2['streams'][0]
        print("音频编码器:", streams2['codec_name'])
        print("采样率:", streams2['sample_rate'])
        print("通道数:", streams2['channels'])
        print("时长:", streams2['duration'])

        # break

def longest_common_substring(str1, str2):
    m = len(str1)
    n = len(str2)
    dp = [[0] * (n + 1) for _ in range(m + 1)]
    max_len = 0
    end_index = 0
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if str1[i - 1] == str2[j - 1]:
                dp[i][j] = dp[i - 1][j - 1] + 1
                if dp[i][j] > max_len:
                    max_len = dp[i][j]
                    end_index = i
    return str1[end_index - max_len:end_index]



def make_videos_from_datas(datas):
    for i in range(len(datas)):
        json_file = datas[i]
        with open(json_file, 'r') as file:
            # 读取文件内容并解析为Python对象
            item = json.load(file)
            name = item['name']
            img1 = item['img1']
            img2 = item['img2']
            audio = item['audio']
            txt1 = item['txt1']
            txt2 = item['txt2']
            audio_text = item['audio_text']

            print('time:', datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") )
            print('make_videos_from_datas [%d]' % i)

            print('name:', name)
            print('img1:', img1)
            print('img2:', img2)
            print('audio:', audio)
            # print('txt1:', txt1)
            # print('txt2:', txt2)
            # print('audio_text:', audio_text)

            output_name =  name + '.mp4'
            output_path =  os.path.join(audio.split('audios')[0], f'mp4/{output_name}')
            if os.path.exists(output_path):
                continue


            txt2_start_txt = txt2[0:30]
            print('txt2_start_txt:', txt2_start_txt)

            common_len = 0
            common_substring = ''
            idx = 0
            for j in range(len(audio_text)):
                item_txt = audio_text[j][0]
                common_sub = longest_common_substring(txt2_start_txt, item_txt)
                sub_len = len(common_sub)

                # print(f'[{j}] sub_len:{sub_len}', common_sub)

                if sub_len > common_len:
                    idx = j
                    common_len = sub_len
                    common_substring = common_sub

            audio_item = audio_text[idx]
            item_txt = audio_item[0]
            # print(idx,'audio_item:', audio_item)

            # 尾部位置
            # offset1 = len(txt2_start_txt) - txt2_start_txt.find(common_substring) - len(common_substring)
            # # 开头位置
            # offset2 = item_txt.find(common_substring)
            # clip1_time = audio_item[1] - 5000 * (offset2/ len(item_txt))
            # 取中间值


            clip1_time = audio_item[1]
            clip1_time = round(clip1_time/1000)

            print('item_txt:', item_txt)
            print('common_substring:', common_substring)
            print('clip1_time:', clip1_time)




            print('output_path:', output_path)
            utils.XmMovie.make_video_smart(output=output_path, img1=img1, img2=img2, audio=audio, clip1_time=clip1_time)



def test1():
    resource = 'resource2'
    month = "01.January"
    # month = "06.June"
    # month = "07.July"
    # month = "08.August"

    files_dict = get_all_files(resource, month)
    names = files_dict['names']
    audios = files_dict['audios']
    imgs = files_dict['imgs']
    datas = get_files(dir=f'{resource}/{month}/datas',exts=['json'])


    # print("names:", json.dumps(names, indent=4, ensure_ascii=False))
    # print("audios:", json.dumps(audios, indent=4, ensure_ascii=False))
    # print("imgs:", json.dumps(imgs, indent=4, ensure_ascii=False))
    print("datas:", json.dumps(datas, indent=4, ensure_ascii=False))

    # convert_wma_wav(f'{resource}/{month}/wma_audios', f'{resource}/{month}/audios')

    # rename_files(origin_names=names, imgs=imgs, wma_audios=wma_audios)

    # make_datas(resource, month, names, imgs, audios)

    # batch_make_video(names=names, imgs=imgs, wma_audios=wma_audios, output_dir=f'{resource}/{month}/mp4')

    make_videos_from_datas(datas)



import ffmpeg


def test2():
    audio_file = './resource1/01.January/audios/初Jan00 Fish in the Street.wav'
    test.test1.demo1(audio_file);

def test3():
    source = 'test/t1.wma'
    # source = 'test/t2.wav'
    out = 'test/t1.wav'
    # wma_audio = AudioSegment.from_file(source, format="wmav2")

    # 使用ffmpeg-python读取音频信息
    # 使用ffmpeg.probe()获取音频文件信息
    info = ffmpeg.probe(source)
    streams = info['streams'][0]
    # print(json.dumps(streams, indent=4))

    print("音频编码器:", streams['codec_name'])
    print("采样率:", streams['sample_rate'])
    print("通道数:", streams['channels'])
    print("时长:", streams['duration'])

    ffmpeg.input(source).output(out).run()

    info2 = ffmpeg.probe(out)
    streams2 = info2['streams'][0]

    print("音频编码器:", streams2['codec_name'])
    print("采样率:", streams2['sample_rate'])
    print("通道数:", streams2['channels'])
    print("时长:", streams2['duration'])

test1()
# test2();
# test3();